//
//  XOShopDetailViewController.m
//  XiOuMall
//
//  Created by lifayu on 2018/2/23.
//  Copyright © 2018年 lifayu. All rights reserved.
//

#import "XOShopDetailViewController.h"

#import "XOShopDetailInfoHeaderReusableView.h"
#import "XOShopDetailSegementControlHeaderReusableView.h"
#import "EJSGoodsCCell.h"
#import "EJSFlashSaleHeaderReusableView.h"
#import "EJSFlashSaleFooterReusableView.h"
#import "EJSHorizontalGoodsCCell.h"
#import "XOShopFlashSaleListRequest.h"
#import "XOShopInfoRequest.h"
#import "EJSGoodsCategoryRequest.h"
#import "EJSGoodsListRequest.h"
#import "EJSSearchViewController.h"
#import "EJSGoodsDetailInfoViewController.h"

@interface XOShopDetailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, UITabBarDelegate>{
    NSInteger _currentPage;
    NSTimer *_flashSaleTimer;
}

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UITabBar *shopDetailTabBar;
@property (strong, nonatomic) NSMutableArray *flashSaleList;
@property (strong, nonatomic) NSMutableArray *goodsCategoryList;
@property (strong, nonatomic) EJSFlashSaleModel * currenFlashSale;
@property (strong, nonatomic) NSMutableArray *shopGoodsList;

@property (strong, nonatomic) EJSCategoryModel *goodsCategoryModel;

@end

@implementation XOShopDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = self.shopModel.shopName;
    _currentPage = 1;
    [self getShopDetailInfo];
    [self getGoodsCategoryList];
    [self getShopFlashSaleList];
    self.shopDetailTabBar.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    if ([item.title isEqualToString:@"全部分类"]) {

    }else if ([item.title isEqualToString:@"商铺动态"]) {

    }else if ([item.title isEqualToString:@"店铺信息"]) {

    }else {

    }
}


- (void)configOwnViews{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    [self.collectionView setCollectionViewLayout:layout];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSHorizontalGoodsCCell" bundle:nil] forCellWithReuseIdentifier:@"EJSHorizontalGoodsCCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSGoodsCCell" bundle:nil] forCellWithReuseIdentifier:@"EJSGoodsCCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"XOShopDetailInfoHeaderReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"XOShopDetailInfoHeaderReusableView"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"XOShopDetailSegementControlHeaderReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"XOShopDetailSegementControlHeaderReusableView"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSFlashSaleHeaderReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"EJSFlashSaleHeaderReusableView"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSFlashSaleFooterReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"EJSFlashSaleFooterReusableView"];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage = 1;
        [self getGoodsList];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self getGoodsList];
    }];
    
    [self configNavigationLeftItemWithImage:[UIImage imageNamed:@"back_icon"]];
    [self configNavigationRightItemWithImage:[UIImage imageNamed:@"search"]];
}

- (void)rightBarButtonAction:(id)sender
{
    EJSSearchViewController *searchVC = [[EJSSearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)setShopModel:(XOShopModel *)shopModel{
    if(_shopModel != shopModel){
        _shopModel = shopModel;
       

        [self.collectionView reloadData];
    }
}

- (void)setGoodsCategoryModel:(EJSCategoryModel *)goodsCategoryModel{
    _goodsCategoryModel = goodsCategoryModel;
    _currentPage = 1;
    [self getGoodsList];
}


#pragma mark - loadData
#pragma mark  获取店铺详情
- (void)getShopDetailInfo{
    XOShopInfoRequest *req = [XOShopInfoRequest new];
    req.shopId = self.shopId;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        self.shopModel = response.data;
    } failHandler:^(BaseResponse *response) {
        
    }];
}

#pragma mark 获取店铺商品分类
- (void)getGoodsCategoryList{
    EJSGoodsCategoryRequest *req = [EJSGoodsCategoryRequest new];
    req.shopId = self.shopId;
    req.type = @"son";
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.goodsCategoryList = response.data;
        if(weakSelf.goodsCategoryList.count > 0){
            weakSelf.goodsCategoryModel = weakSelf.goodsCategoryList.firstObject;
        }
        [weakSelf.collectionView reloadData];
    } failHandler:^(BaseResponse *response) {
        
    }];
}

#pragma mark 获取商品列表
- (void)getGoodsList{
    EJSGoodsListRequest *req = [EJSGoodsListRequest new];
    req.shopId = self.shopId;
    req.page = @(_currentPage).stringValue;
    req.pageLimit = @"20";
    req.categoryId = self.goodsCategoryModel.categoryId;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        EJSGoodsListModel *listModel = response.data;
        if(listModel){
            if(listModel.totalPages.integerValue == listModel.page.integerValue || listModel.totalPages.integerValue == 0){
                [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            if(_currentPage == 1){
                weakSelf.shopGoodsList = [NSMutableArray arrayWithArray:listModel.list];
            }else{
                [weakSelf.shopGoodsList addObjectsFromArray:listModel.list];
            }
        }else{
            [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
        [weakSelf.collectionView reloadData];
    } failHandler:^(BaseResponse *response) {
        
    }];
}

#pragma mark  限时抢购
- (void)getShopFlashSaleList{
    FlyWeakSelf
    XOShopFlashSaleListRequest *req = [XOShopFlashSaleListRequest new];
    req.shopId = self.shopId;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        weakSelf.flashSaleList = [NSMutableArray arrayWithArray:response.data];
        if(weakSelf.flashSaleList.count > 0){
            weakSelf.currenFlashSale = weakSelf.flashSaleList.firstObject;
        }
        [self.collectionView.mj_header endRefreshing];
    } failHandler:^(BaseResponse *response) {
        
    }];
}
- (void)setCurrenFlashSale:(EJSFlashSaleModel *)currenFlashSale{
    if(_currenFlashSale != currenFlashSale){
        _currenFlashSale = currenFlashSale;
        if(_flashSaleTimer){
            [_flashSaleTimer invalidate];
            _flashSaleTimer = nil;
        }
        if([self flashSaleUnderway]){
            _flashSaleTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(flashSaleTimerCountDown) userInfo:nil repeats:YES];
            [_flashSaleTimer fire];
        }
        [self.collectionView reloadData];
    }
}

- (BOOL)flashSaleUnderway{
    NSDate *flashStartDate = [self convertStringToDate:self.currenFlashSale.startTime];
    NSDate *flashEndDate = [self convertStringToDate:self.currenFlashSale.endTime];
    NSComparisonResult result = [[self localDate] compare:flashStartDate];
    NSComparisonResult result2 = [[self localDate] compare:flashEndDate];
    if((result == NSOrderedDescending || result == NSOrderedSame) && (result2 == NSOrderedAscending || result2 == NSOrderedSame)){
        return YES;
    }
    return NO;
}
- (NSDate *)localDate{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    return  [date  dateByAddingTimeInterval: interval];
}

- (NSDate *)convertStringToDate:(NSString *)string{
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];//时间管理
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    NSDate *date = [formatter dateFromString:string];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    return  [date dateByAddingTimeInterval:interval];
}

- (void)flashSaleTimerCountDown{
    NSDate *flashSaleEndDate = [self convertStringToDate:self.currenFlashSale.endTime];
    NSDate *localDate = [self localDate];
    NSTimeInterval start = (NSInteger)[localDate timeIntervalSince1970]*1;
    NSTimeInterval end = (NSInteger)[flashSaleEndDate timeIntervalSince1970]*1;
    
    NSTimeInterval timeStamp = end - start;
    if(timeStamp > 0){
        int second = (int)timeStamp%60;//秒
        int minute = (int)timeStamp/60%60;
        int hour = (int)timeStamp/3600;
        NSString *hourString  = [NSString stringWithFormat:@"%02d",hour];
        NSString *minuteString  = [NSString stringWithFormat:@"%02d",minute];
        NSString *secondString  = [NSString stringWithFormat:@"%02d",second];
                
        EJSFlashSaleHeaderReusableView *flashSaleHeaderView = (EJSFlashSaleHeaderReusableView *)[self.collectionView supplementaryViewForElementKind:UICollectionElementKindSectionHeader atIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
        if([flashSaleHeaderView isKindOfClass:[EJSFlashSaleHeaderReusableView class]] && flashSaleHeaderView.hTimeLabel && flashSaleHeaderView.mTimeLabel && flashSaleHeaderView.sTimeLabel){
            flashSaleHeaderView.timeCover.hidden = NO;
            flashSaleHeaderView.hTimeLabel.text = hourString;
            flashSaleHeaderView.mTimeLabel.text = minuteString;
            flashSaleHeaderView.sTimeLabel.text = secondString;
        }
    }else{
        [self.flashSaleList removeObject:self.currenFlashSale];
        if(self.flashSaleList.count > 0){
            self.currenFlashSale = self.flashSaleList.firstObject;
        }else{
            self.currenFlashSale = nil;
        }
    }
}


#pragma mark - UICollectionViewDataSoruce
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(section == 1){
        if(_currenFlashSale){
             return 1;
        }
    }
    if(section == 2){
        return self.shopGoodsList.count;
    }
    return 0;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        EJSHorizontalGoodsCCell *horizontalGoodsCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSHorizontalGoodsCCell" forIndexPath:indexPath];
 
        [horizontalGoodsCell setGoodsList:self.currenFlashSale.goods];
        return horizontalGoodsCell;
    }else {
        EJSGoodsCCell *goodsCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSGoodsCCell" forIndexPath:indexPath];
        [goodsCell setGoodsModel:self.shopGoodsList[indexPath.item]];
        return goodsCell;
    }
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    UICollectionViewFlowLayout *flowLayout = collectionViewLayout;
    flowLayout.sectionHeadersPinToVisibleBounds = YES;
    if(section == 0){
        return CGSizeMake(ScreenWidth, 150);
    }
    if(section == 1){
        if(self.flashSaleList.count > 0){
            return CGSizeMake(ScreenWidth, 89);
        }
    }
    if(section == 2 && self.goodsCategoryList.count > 0){
        return CGSizeMake(ScreenWidth, 50);
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{

    if(self.flashSaleList.count > 0 && section == 1){
        return CGSizeMake(ScreenWidth, 76);
    }
    return CGSizeZero;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        if([kind isEqualToString:UICollectionElementKindSectionHeader]){
            XOShopDetailInfoHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"XOShopDetailInfoHeaderReusableView" forIndexPath:indexPath];
            [headerView setShopModel:self.shopModel];
            return headerView;
        }
    }
    if(indexPath.section == 1){
        if([kind isEqualToString:UICollectionElementKindSectionHeader]){
            EJSFlashSaleHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EJSFlashSaleHeaderReusableView" forIndexPath:indexPath];
            if([self flashSaleUnderway]){
                [self flashSaleTimerCountDown];
                headerView.statusLabel.text = @"抢购中";
            }else{
                headerView.timeCover.hidden = YES;
                headerView.statusLabel.text = [NSString stringWithFormat:@"下一场抢购 %@ 开始", self.currenFlashSale.startTime];
            }
            return headerView;
        }else{
            EJSFlashSaleFooterReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EJSFlashSaleFooterReusableView" forIndexPath:indexPath];
            [footerView.nextButton addTarget:self action:@selector(nextFlashSaleAction) forControlEvents:UIControlEventTouchUpInside];
            return footerView;
        }
    }
    
    if(indexPath.section == 2){
        if([kind isEqualToString:UICollectionElementKindSectionHeader]){
            XOShopDetailSegementControlHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"XOShopDetailSegementControlHeaderReusableView" forIndexPath:indexPath];
            NSMutableArray *categoryTitleList = [NSMutableArray array];
            for (EJSCategoryModel *categoryModel in self.goodsCategoryList) {
                if(categoryModel.categoryName){
                    [categoryTitleList addObject:categoryModel.categoryName];
                }else{
                    [categoryTitleList addObject:@""];
                }
            }
            headerView.segmentedControl.sectionTitles = categoryTitleList;
            [headerView.segmentedControl addTarget:self
                                             action:@selector(segmentedControlValueChanged:)
                                   forControlEvents:UIControlEventValueChanged];
            return headerView;
        }
        
    }
    return nil;
}

- (void)nextFlashSaleAction{
    if(self.flashSaleList.count > 0){
        NSInteger index = [self.flashSaleList indexOfObject:_currenFlashSale];
        if(index + 1 < self.flashSaleList.count){
            self.currenFlashSale = self.flashSaleList[index + 1];
            [self.collectionView reloadData];
        }else{
            [[HUDHelper sharedInstance] tipMessage:@"暂无下一场抢购"];
        }
    }else{
        [[HUDHelper sharedInstance] tipMessage:@"暂无下一场抢购"];
    }
}

#pragma mark HMSegmentedControl target

- (void)segmentedControlValueChanged:(HMSegmentedControl*)segmentedControl{
    NSInteger selectedIndex = segmentedControl.selectedSegmentIndex;
    if(selectedIndex < self.goodsCategoryList.count){
        self.goodsCategoryModel = self.goodsCategoryList[selectedIndex];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if(section == 2){
        return UIEdgeInsetsMake(15, 15, 15, 15);
    }
    return UIEdgeInsetsZero;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (ScreenWidth - 45)/2;
    CGFloat height = width + 52;
    return CGSizeMake(width, height);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 2){
        EJSGoodsModel *goodsModel = self.shopGoodsList[indexPath.item];
        EJSGoodsDetailInfoViewController *goodsDetailVC = [[EJSGoodsDetailInfoViewController alloc] init];
        goodsDetailVC.goodsId = goodsModel.spuId;
//        goodsDetailVC.shopId = goodsModel.shopId;
        [self.navigationController pushViewController:goodsDetailVC animated:YES];
    }
}

@end
